<script setup lang="ts">

import VChart from "vue-echarts";
import {ElOption, ElSelect} from "element-plus";
import {computed, ref, watch} from "vue";
import type {SaleData} from "../model/sale.ts";
import * as echarts from "echarts/core";
import {CanvasRenderer} from "echarts/renderers";
import {BarChart, LineChart} from "echarts/charts";
import {
  GridComponent,
  LegendComponent,
  SingleAxisComponent,
  TitleComponent,
  TooltipComponent
} from "echarts/components";

const props = defineProps({
  rawList: {
    type: Array<SaleData>,
    required: true
  }
})
// 1. 先注册ECharts组件（确保后续使用不报错）
echarts.use([
  CanvasRenderer,
  BarChart, LineChart,
  TitleComponent, GridComponent,
  TooltipComponent, LegendComponent,
  SingleAxisComponent
]);

// 2. 定义接口类型（先定义类型，再用）
interface Dimension {
  key: keyof SaleData;
  label: string;
}
const medicineTypes = computed(() => [...new Set(props.rawList.map(item => item.medicine || '未知'))]);

const filterKey = ref<keyof SaleData | ''>('');
const filterValues = ref<string[]>([]);
const chartType = ref<'bar' | 'line'>('bar');
const xAxisDimension = ref<keyof SaleData>('sales_rep');
const allDimensions: Dimension[] = [
  {key: 'sales_rep', label: '销售代表'},
  {key: 'medicine', label: '药品'},
  {key: 'brand', label: '品牌'},
  {key: 'store_name', label: '门店'},
  {key: 'sale_date', label: '销售日期'},
];
const xAxisDimensions: Dimension[] = allDimensions.filter(d => d.key !== 'medicine');
const filteredData = computed<SaleData[]>(() => {
  return props.rawList.filter(item => {
    // 过滤字段筛选
    if (filterKey.value && filterValues.value.length > 0) {
      const itemValue = String(item[filterKey.value] ?? '未知');
      if (!filterValues.value.includes(itemValue)) return false;
    }
    return true;
  });
});
// 图表系列数据（带数值显示）
const chartSeriesData = computed(() => {
  const xAxisValues = [...new Set(
      filteredData.value.map(item => String(item[xAxisDimension.value] || '未知'))
  )];
  const series = medicineTypes.value.map(medicine => {
    return {
      name: medicine,
      type: chartType.value,
      data: xAxisValues.map(xValue => {
        const filteredItems = filteredData.value.filter(item =>
            String(item[xAxisDimension.value]) === xValue && item.medicine === medicine
        );
        return filteredItems.reduce((sum, item) => sum + (item.sale_total || 0), 0);
      }),
      label: {
        show: true,
        position: chartType.value === 'bar' ? 'top' : 'top',
        fontSize: 12,
        color: '#333'
      },
      itemStyle: {
        borderRadius: chartType.value === 'bar' ? 4 : 0
      }
    };
  });
  return {xAxisValues, series};
});

// 6. 图表配置函数（依赖chartSeriesData，放在computed后）
function getChartOption() {
  const {xAxisValues, series} = chartSeriesData.value;
  const xAxisLabel = allDimensions.find(d => d.key === xAxisDimension.value)?.label || '维度';

  return {
    title: {text: `${xAxisLabel} 各药品销量统计`, left: 'center'},
    tooltip: {
      trigger: 'axis',
      formatter: (params: any[]) => {
        const xValue = params[0].axisValue;
        let tip = `<div>${xValue}</div>`;
        params.forEach(item => {
          tip += `<div>${item.seriesName}：${item.value} 件</div>`;
        });
        return tip;
      }
    },
    legend: {data: medicineTypes.value, top: 50, center: 'center'},
    grid: {left: '3%', right: '4%', bottom: '10%', containLabel: true},
    xAxis: {type: 'category', data: xAxisValues, axisLabel: {rotate: 30, interval: 0}},
    yAxis: {type: 'value', name: '销售数量（件）'},
    series: series,
    barGap: '0%',
    barCategoryGap: '20%'
  };
}

// 7. 初始化图表配置（必须在getChartOption定义后）
const chartOption = ref<echarts.EChartsCoreOption>(getChartOption());

// X轴维度变化
const handleXAxisChange = () => {
};

// 图表类型变化
// const handleChartTypeChange = () => {
// };

// 9. 监听筛选条件变化，刷新图表
watch([filteredData, chartType, xAxisDimension], () => {
  chartOption.value = {...getChartOption()};
}, {immediate: true});
</script>

<template>


  <!-- 维度选择区 -->
  <div class="filter-row">
    <label>统计维度（X轴）</label>
    <el-select
        v-model="xAxisDimension"
        placeholder="请选择X轴维度"
        @change="handleXAxisChange"
    >
      <el-option
          v-for="d in xAxisDimensions"
          :key="d.key"
          :label="d.label"
          :value="d.key"
      ></el-option>
    </el-select>
  </div>

  <!-- 图表展示区 -->
  <div class="chart-container">
    <v-chart
        :option="chartOption"
        autoresize
        style="width: 100%; height: 400px;"
        v-if="filteredData.length > 0"
        :key="xAxisDimension + chartType"
    />
    <div class="empty-state" v-else>
      <p>暂无数据，请调整筛选条件</p>
    </div>
  </div>
</template>

<style scoped>

/* 筛选区样式优化 */
.filter-row {
  display: flex;
  align-items: center;
  gap: 16px; /* 加大间距，避免拥挤 */
  flex-wrap: wrap;
  margin: 20px 0;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}

</style>